package com.jk.vehicle.mini.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 数据查询相关工具列
 * @author zhangdongdong
 * @date 2019/11/28
 */
public class QueryUtil {
	/**
	 * 查询条件封装
	 * @param criteria tk 查询条件实体类
	 * @param paramMap 页面传递查询条件
	 * @param propertyMap 待查询表实体类字段值
	 * @param condition tk 查询条件实体类
	 */
	public static void spliceQueryParam(Example.Criteria criteria, Map<String, Object> paramMap, Map<String, EntityColumn> propertyMap, Condition condition){
		// 遍历查询Map
		for(Map.Entry<String, Object> entry : paramMap.entrySet()){
			String mapKey = entry.getKey();
			// 如果查询条件不是表中字段，自动过滤掉
			if (!propertyMap.containsKey(mapKey)){
				continue;
			}
			Object mapVal = entry.getValue();
			if (mapVal != null){
				// 特殊查询方式，JSON字符串
				if (mapVal.toString().startsWith("{")){
					JSONObject valObject = JSON.parseObject(mapVal.toString());
					if ("like".equals(valObject.getString("type"))){
						criteria.andLike(mapKey, "%" + valObject.getString("val") + "%");
					}
					if ("leftLike".equals(valObject.getString("type"))){
						criteria.andLike(mapKey, "%" + valObject.getString("val"));
					}
					if ("rightLike".equals(valObject.getString("type"))){
						criteria.andLike(mapKey, valObject.getString("val") + "%");
					}
					if ("notIn".equals(valObject.getString("type"))){
						String val = valObject.getString("val");
						List<String> valList = Arrays.asList(val.split(","));
						criteria.andNotIn(mapKey, valList);
					}
					if ("in".equals(valObject.getString("type"))){
						String val = valObject.getString("val");
						List<String> valList = Arrays.asList(val.split(","));
						criteria.andIn(mapKey, valList);
					}
					if ("greaterThanOrEqualTo".equals(valObject.getString("type"))){
						String val = valObject.getString("val");
						criteria.andGreaterThanOrEqualTo(mapKey, val);
					}
					if ("lessThanOrEqualTo".equals(valObject.getString("type"))){
						String val = valObject.getString("val");
						criteria.andLessThanOrEqualTo(mapKey, val);
					}
					if ("between".equals(valObject.getString("type"))){
						String val1 = valObject.getString("val1");
						String val2 = valObject.getString("val2");
						criteria.andBetween(mapKey, val1, val2);
					}
					if ("desc".equals(valObject.getString("type"))){
						condition.orderBy(mapKey).desc();
					}
					if ("asc".equals(valObject.getString("type"))){
						condition.orderBy(mapKey).asc();
					}
				}else{
					//  默认查询方式
					criteria.andEqualTo(mapKey, mapVal);
				}
			}
		}
	}
}
